package com.generator.mybatisplus;

import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.draw.DashedLine;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.LineSeparator;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.property.UnitValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class ACx {


    @Test
    public void ePdf () {
        String dest = "d:/home/example.pdf";
        try {
            PdfWriter writer = new PdfWriter(dest);
            PdfDocument pdf = new PdfDocument(writer);
            Document document = new Document(pdf,PageSize.A4);

            //document.add(new Paragraph("Hello, World!"));
            //document.add(new Paragraph("This is a sample PDF created using iText 1."));
            Sheet sheet = getSheet();
            int width = (int) (sheet.getColumnWidthInPixels(0) * sheet.getRow(0).getLastCellNum()); // Example width calculation
            int height = (sheet.getLastRowNum() + 1) * 30; // Example height calculation, adjust as needed
            // 创建图像
            //int width = 800;
            //int height = 600;
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            graphics.setColor(Color.BLACK);

            PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
            document.setFont(font).setFontSize(10);
            document.add(new Paragraph().add(new Text("询价啊询价").setFontSize(20).setBold()));
            // 创建一个 LineSeparator 对象
            LineSeparator line = new LineSeparator(new com.itextpdf.kernel.pdf.canvas.draw.SolidLine());
            // 设置线与上方文本的间距
            line.setMarginTop(10); // 20 点的间距
            // 设置线与下方文本的间距
            line.setMarginBottom(20); // 20 点的间距
            line.setFontColor(new DeviceRgb(255, 0, 0));
            // 将线添加到文档中
            document.add(line);

            //float [] pointColumnWidths = {300F, 300F};
            Table table = new Table(UnitValue.createPercentArray(3)).useAllAvailableWidth();

            table.addCell(new com.itextpdf.layout.element.Cell().add(new Paragraph("序号").addAll(
                    Lists.newArrayList(new Text("询价日期："), new Text("2323").setBold())
            )).setBorder(Border.NO_BORDER));
            table.addCell(new com.itextpdf.layout.element.Cell().add(new Paragraph("序号").addAll(
                    Lists.newArrayList(new Text("询价日期："), new Text("2323").setBold())
            )).setBorder(Border.NO_BORDER));
            table.addCell(new com.itextpdf.layout.element.Cell().add(new Paragraph("序号").addAll(
                    Lists.newArrayList(new Text("询价日期："), new Text("2323").setBold())
            )).setBorder(Border.NO_BORDER));

            table.addCell(new com.itextpdf.layout.element.Cell().add(new Paragraph("序号").addAll(
                    Lists.newArrayList(new Text("询价日期2："), new Text("2323").setBold())
            )).setBorder(Border.NO_BORDER));
            table.addCell(new com.itextpdf.layout.element.Cell(1, 2).add(new Paragraph("序号").addAll(
                    Lists.newArrayList(new Text("询价日期21："), new Text("2323").setBold())
            )).setBorder(Border.NO_BORDER));

            table.addCell(new com.itextpdf.layout.element.Cell(1, 2).add(new Paragraph("序号").addAll(
                    Lists.newArrayList(new Text("网站："), new Text("cc").setBold())
            )).setBorder(Border.NO_BORDER));
            document.add(table);
            DashedLine dashedLine = new DashedLine();
            dashedLine.setColor(ColorConstants.CYAN); // 设置虚线颜色为红色
            // 创建 LineSeparator 对象
            LineSeparator line2 = new LineSeparator(dashedLine);
            // 设置线与上方文本的间距
            line2.setMarginTop(10); // 20 点的间距
            // 设置线与下方文本的间距
            line2.setMarginBottom(20); // 20 点的间距
            // 将线添加到文档中
            document.add(line2);
            // 渲染 Excel 内容到图像
            int startX = 10;
            int startY = 20;
            int rowHeight = 20;
            int y = 1;
            for (Row row : sheet) {
                float yPosition = row.getRowNum() * 20; // Adjust based on font size and style
                for (Cell cell : row) {
                    float xPosition = cell.getColumnIndex() * sheet.getColumnWidthInPixels(cell.getColumnIndex()); // Adjust based on column width and index
                    graphics.drawString(getText(cell), xPosition, yPosition); // Adjust based on font size and style
                }
                    //startX += 100;

                //startX = 10;
                startY += rowHeight;
            }

            // 保存图像
            ImageIO.write(image, "png", new File("workbook_screenshot.png"));

            com.itextpdf.layout.element.Image pdfImage = new com.itextpdf.layout.element.Image(ImageDataFactory.create("workbook_screenshot.png"));
            //document.add(pdfImage);
            document.close();
            pdf.close();
            graphics.dispose();
        } catch (IOException e) {
            log.info("错误:{}",e);
        }catch (Exception e) {
            log.info("错误:{}",e);
        }
    }

    private String getText(Cell cell) {
        if (cell == null) return "";
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return cell.toString(); // For other types, use toString or handle as needed
        }
    }

    private Sheet getSheet () {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("生鲜采购清单");

        // 设置表头
        Row headerRow = sheet.createRow(0);
        CellStyle style = sheet.getWorkbook().createCellStyle();
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        List<String> headers = Arrays.asList("菜品名称", "供应商", "单位", "单价", "订购数量", "总价");
        for (int i = 0; i < headers.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(headers.get(i));
        }
        int rowIndex = 1;
        Row dataRow = sheet.createRow(rowIndex++);
        dataRow.createCell(0).setCellValue("采购日期");
        dataRow.createCell(1).setCellValue("2025-2-13 09:35:16");
        dataRow = sheet.createRow(rowIndex++);
        dataRow.createCell(0).setCellValue("下单供应商");
        dataRow.createCell(1).setCellValue("put.getProviderName()");
        dataRow = sheet.createRow(rowIndex++);
        dataRow.createCell(0).setCellValue("操作人");
        dataRow.createCell(1).setCellValue("apply.getOperateUserName()");
        dataRow = sheet.createRow(rowIndex++);
        dataRow.createCell(0).setCellValue("采购总金额");
        dataRow.createCell(1).setCellValue("cellValueBigDecimal(totalPriceSum)");
        return sheet;
    }

    @Test
    public void pdfUrl() {
        String url = "https://tool.lu/"; // 替换为目标 URL
        String outputPdfPath = "d:/home/output.pdf"; // 输出 PDF 文件路径
        //System.setProperty("webdriver.chrome.driver", "D:\\an1\\chrome\\");
        // 1. 设置 WebDriver
        System.out.println(System.getProperty("webdriver.chrome.driver"));
        // 1. 指定 chromedriver.exe 的路径
        ChromeDriverService service = new ChromeDriverService.Builder()
                .usingDriverExecutable(new File("D:/an1/chrome/chromedriver.exe"))
                .withSilent(true) // 静默模式，不输出日志
                .build();
        WebDriver driver = new ChromeDriver(service);

        try {
            // 2. 打开 URL 并渲染页面
            driver.get(url);
            String htmlContent = driver.getPageSource();

            // 3. 将 HTML 转换为 PDF
            HtmlConverter.convertToPdf(htmlContent, new FileOutputStream(outputPdfPath));

            System.out.println("PDF 文件已生成: " + outputPdfPath);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("生成 PDF 失败: " + e.getMessage());
        } finally {
            // 4. 关闭 WebDriver
            driver.quit();
        }
    }
}
